package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.gulimall.product.service.AttrService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.ProductAttrValueDao;
import com.atguigu.gulimall.product.entity.ProductAttrValueEntity;
import com.atguigu.gulimall.product.service.ProductAttrValueService;


@Service("productAttrValueService")
public class ProductAttrValueServiceImpl extends ServiceImpl<ProductAttrValueDao, ProductAttrValueEntity> implements ProductAttrValueService {

    @Autowired
    AttrService attrService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ProductAttrValueEntity> page = this.page(
                new Query<ProductAttrValueEntity>().getPage(params),
                new QueryWrapper<ProductAttrValueEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<ProductAttrValueEntity> baseAttrListforspu(Long spuId) {
        List<ProductAttrValueEntity> valueEntityList = this.list(
                new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        return valueEntityList;
    }

    /**
     * 获取sku所对应的属性即spu对应的属性
     * @return
     * @param spuId
     */
    @Override
    public List<SkuEsModel.Attr> getSkuAttrs(Long spuId) {
        // 获取对应的productAttrValue集合
        List<ProductAttrValueEntity> valueEntityList = this.list(
                new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));

        List<Long> collect = valueEntityList.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());


        List<Long> attrIds = attrService.getIdINAttrIds(collect);

        // 过滤返回可以被检索的属性
        List<SkuEsModel.Attr> collect1 = valueEntityList.stream().filter(item -> {
            return attrIds.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attr attr = new SkuEsModel.Attr();
            BeanUtils.copyProperties(item, attr);
            return attr;
        }).collect(Collectors.toList());

        return collect1;
    }

}